import sys

from magic_number import extract_magic_number_def, manage_magic_number, get_magic_number_summary
from type_def import manage_type_def, get_type_def_summary
from type_trans import manage_type_trans, get_type_trans_summary
from assert_rd import manage_assert, get_assert_summary

from glob import glob
import os
import json

def manage_readability(c_dir, rust_input_dir, rust_output_dir):
    input_file_list = glob(os.path.join(rust_input_dir, '**', '*.*'), recursive=True)
    # print(os.path.join(rust_input_dir, '**', '**'), input_file_list)
    file_dict = {}
    for filename in input_file_list:
        if os.path.isfile(os.path.join(rust_input_dir, filename)):

            rel_dir_path = os.path.dirname(os.path.relpath(filename, rust_input_dir))
            os.makedirs(os.path.join(rust_output_dir, rel_dir_path), exist_ok=True)

        # if os.path.isfile(os.path.join(rust_input_dir, filename)):
            if filename.endswith('.rs') and filename.find('src') != -1:
                with open(filename, 'r') as f:
                    file_content = f.read()
                file_dict[os.path.relpath(filename, rust_input_dir)] = file_content
            else:
                with open(filename, 'rb') as f:
                    file_content = f.read()
                with open(os.path.join(rust_output_dir, os.path.relpath(filename, rust_input_dir)), 'wb') as f:
                    f.write(file_content)

    extract_magic_number_def(c_dir)

    # print(file_dict.keys())

    process_summary_dict = {}

    for filename, file_content in file_dict.items():
        file_content = manage_assert(file_content)
        file_content = manage_type_def(file_content)
        file_content = manage_type_trans(file_content)
        file_content = manage_magic_number(file_content)
        with open(os.path.join(rust_output_dir, filename), 'w') as f:
            f.write(file_content)


#     process_summary_dict.update(get_assert_summary())
    process_summary_dict.update(get_magic_number_summary())
    process_summary_dict.update(get_type_def_summary())
    process_summary_dict.update(get_type_trans_summary())
    print(process_summary_dict)
    process_summary_str = json.dumps(process_summary_dict, indent=4, ensure_ascii=False)
    with open(os.path.join(rust_output_dir, 'readability_summary.json'), 'w', encoding='utf-8') as f:
        f.write(process_summary_str)

if __name__ == '__main__':
    manage_readability(sys.argv[1], sys.argv[2], sys.argv[3])
